package com.ziyun.erp.modules.member.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.service.common.constant.AppType;
import com.service.common.model.UserInfo;
import com.service.common.utils.PasswordUtil;
import com.service.ucenter.api.UserLoginService;
import com.service.ucenter.constant.UcenterResult;
import com.service.ucenter.model.login.RegisterParamDto;
import com.ziyun.erp.common.e.member.UserTypeEnum;
import com.ziyun.erp.common.utils.JsonUtils;
import com.ziyun.erp.common.utils.MD5;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.erpUserLog.entity.ErpUserLogEntity;
import com.ziyun.erp.modules.erpUserLog.service.ErpUserLogService;
import com.ziyun.erp.modules.member.dao.*;
import com.ziyun.erp.modules.member.entity.*;
import com.ziyun.erp.modules.member.service.UserBaseInfoService;
import com.ziyun.erp.modules.member.service.UserLoginAccountService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("userBaseInfoService")
public class UserBaseInfoServiceImpl extends ServiceImpl<UserBaseInfoDao, UserBaseInfoEntity> implements UserBaseInfoService {

    @Autowired
    private UserBaseInfoDao userBaseInfoDao;
    @Autowired
    private UserWalletDao userWalletDao;
    @Autowired
    private UserAdvanceDao userAdvanceDao;
    @Autowired
    private UserCreditDao userCreditDao;
    @Autowired
    private UserPointDao userPointDao;
    @Autowired
    private UserMemberLevelDao userMemberLevelDao;
    @Autowired
    private UserLoginAccountDao userLoginAccountDao;
    @Autowired
    private ErpUserLogService erpUserLogService;
    @Autowired
    private UserLoginService userLoginServicel;
    @Autowired
    private UserLoginAccountService userLoginAccountService;

    @Override
    public R list(Map<String, Object> params) {
        PageUtils page = this.selectAllList(params);
        // 存放枚举类到userdata
        Map<String, List> mapEnum = new HashMap<>();
        mapEnum.put("userTypeEnum", JsonUtils.enumToList(UserTypeEnum.class));
        return R.ok().put("page", page).put("userData", mapEnum);
    }

    @Override
    public R listMall(Map<String, Object> params) {
        PageUtils page = this.selectAllListMall(params);
        // 存放枚举类到userdata
        Map<String, List> mapEnum = new HashMap<>();
        mapEnum.put("userTypeEnum", JsonUtils.enumToList(UserTypeEnum.class));
        return R.ok().put("page", page).put("userData", mapEnum);
    }

    @Override
    public Map<String, Object> delete(String ids) {
        Map<String, Object> map = new HashMap<String, Object>();
        int res = 0;
        if (StringUtils.isNotBlank(ids)) {
            res = this.deleteUsers(ids);
            if (res > 0) {
                map.put("code", res);
                map.put("msg", "删除成功！");
            } else {
                map.put("code", res);
                map.put("msg", "删除失败！");
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> selectByIda(Integer userId) {
        return userBaseInfoDao.selectByIda(userId);
    }

    @Override
    public int updateUserBaseInfo(UserBaseInfoEntity userBaseInfo) {
        return userBaseInfoDao.updateUserBaseInfo(userBaseInfo);
    }

    @Override
    public UserBaseInfoEntity getEntityByuserId(Integer userId) {
        return this.selectOne(new EntityWrapper<UserBaseInfoEntity>().eq("user_id", userId)
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> memRecharge(MemRechargeVO memRecharge, SysUserEntity curentUser) {
        ErpUserLogEntity erpUserLogEntity = new ErpUserLogEntity();
        erpUserLogEntity.setUserId(memRecharge.getUserId());
        erpUserLogEntity.setCreateBy(curentUser.getUsername());

        Map<String, Object> map = new HashMap<String, Object>();

        //充值填写的推荐码=user_base_info表的userId
        if (memRecharge.getRechargeCode() != null && this.getEntityByuserId(memRecharge.getRechargeCode()) == null) {
            map.put("code", 1);
            map.put("msg", "推荐码不存在！");
            return map;
        }

        //会员ID
        Integer userId = memRecharge.getUserId();
        //充值推荐码
        Integer rechargeCode = memRecharge.getRechargeCode();
        //充值金额
        BigDecimal rechargeCount = memRecharge.getRechargeCount();
        //充值类型
        String rechargeType = memRecharge.getRechargeType();
        //备注
        String message = memRecharge.getMessage();

        int m = 0, n = 0;
        //查询当前用户钱包,里面有预存款 信用额度 积分
        UserWalletEntity userWalletEntity = userWalletDao.selectById(userId);
        UserWalletEntity userWallet = new UserWalletEntity();
        userWallet.setUserId(userId);

        //预存款充值
        if ("advance".equals(rechargeType)) {
            BigDecimal count = rechargeCount;
            BigDecimal advance = userWalletEntity.getAdvance();
            BigDecimal logValue = advance;
            advance = advance.add(count);
            if (advance.compareTo(new BigDecimal("0")) < 0) {
                return R.error("用户总预存款不能为负数");
            }
            //更新钱包预存款
            userWallet.setAdvance(advance);
            m = userWalletDao.update(userWallet, new EntityWrapper<UserWalletEntity>().eq("user_id", userId));
            UserAdvanceEntity userAdvanceEntity = new UserAdvanceEntity();
            userAdvanceEntity.setUserId(userId);
            userAdvanceEntity.setMemberAdvance(advance);
            userAdvanceEntity.setMoney(count);
            userAdvanceEntity.setMessage(message==""?UserUtils.getCurentUser().getUsername()+"ERP预存款充值":message);
            userAdvanceEntity.setImportMoney(count);
            userAdvanceEntity.setMempayCode(rechargeCode);
            userAdvanceEntity.setPaymethod("现金存入");
            userAdvanceEntity.setMtime(new Date());
            userAdvanceEntity.setCreateName(curentUser.getUsername());
            n = userAdvanceDao.insert(userAdvanceEntity);
            //记录操作日志
            erpUserLogEntity.setLog("ERP系统充值:会员ID(" + memRecharge.getUserId() + ")预存款增加" + count);
            erpUserLogService.insert(erpUserLogEntity);
            if (m < 1 || n < 1) {
                throw new RRException("充值失败!请联系系统管理员!");
            }
        }
        //信用额度充值
        if ("creditUse".equals(rechargeType)) {
            BigDecimal count = rechargeCount;
            BigDecimal creditUse = userWalletEntity.getCreditUse();
            BigDecimal logValue = creditUse;
            creditUse = creditUse.add(count);
            if (creditUse.compareTo(new BigDecimal("0")) < 0) {
                return R.error("用户总信用额度不能为负数");
            }
            //更新钱包信用额度
            userWallet.setCreditUse(creditUse);
            if ((count.intValue()+userWalletEntity.getCreditLimit())<0){
                userWallet.setCreditLimit(0);
            }else {
                userWallet.setCreditLimit(count.intValue()+userWalletEntity.getCreditLimit());
            }
            m = userWalletDao.update(userWallet, new EntityWrapper<UserWalletEntity>().eq("user_id", userId));
            UserCreditEntity userCreditEntity = new UserCreditEntity();
            userCreditEntity.setUserId(userId);
            userCreditEntity.setMoney(count);
            userCreditEntity.setCreditUse(creditUse);
            userCreditEntity.setMempayCode(rechargeCode);
            userCreditEntity.setMessage(message==""?UserUtils.getCurentUser().getUsername()+"ERP信用额充值":message);
            n = userCreditDao.insert(userCreditEntity);

            //记录操作日志
            erpUserLogEntity.setLog("系统充值:会员ID(" + memRecharge.getUserId() + ")增加信用额" + count);
            erpUserLogService.insert(erpUserLogEntity);
            if (m < 1 || n < 1) {
                throw new RRException("充值失败!请联系系统管理员!");
            }
        }
        //积分充值
        if ("point".equals(rechargeType)) {
            Integer count = rechargeCount.intValue();
            Integer logValue = userWalletEntity.getPoint();
            Integer point = userWalletEntity.getPoint() + count;
            //更新钱包积分
            userWallet.setPoint(point);
            m = userWalletDao.update(userWallet, new EntityWrapper<UserWalletEntity>().eq("user_id", userId));
            UserPointEntity userPointEntity = new UserPointEntity();
            userPointEntity.setUserId(userId);
            userPointEntity.setPoint(point);
            userPointEntity.setChangePoint(count);
            userPointEntity.setRemark(message==""?UserUtils.getCurentUser().getUsername()+"ERP积分充值":message);
            userPointEntity.setMempayCode(rechargeCode);
            n = userPointDao.insert(userPointEntity);

            //记录操作日志
            erpUserLogEntity.setLog("系统充值:会员ID(" + memRecharge.getUserId() + ")增加会员积分" + count);
            erpUserLogService.insert(erpUserLogEntity);
            if (m < 1 || n < 1) {
                throw new RRException("充值失败!请联系系统管理员!");
            }
        }
        //经验值充值
        if ("experience".equals(rechargeType)) {
            UserMemberLevelEntity userMemberLevelEntity = userMemberLevelDao.selectById(userId);
            Integer count = rechargeCount.intValue();
            Integer logValue = userMemberLevelEntity.getExperience();
            Integer experience = userMemberLevelEntity.getExperience() + count;
            userMemberLevelEntity.setExperience(experience);
            n = userMemberLevelDao.updateById(userMemberLevelEntity);

            //记录操作日志
            erpUserLogEntity.setLog("系统充值:会员ID(" + memRecharge.getUserId() + ")增加会员经验值" + count);
            erpUserLogService.insert(erpUserLogEntity);
            if (n < 1) {
                throw new RRException("充值失败!请联系系统管理员!");
            }
        }
        map.put("code", 0);
        map.put("msg", "充值成功！");
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> resetPassword(Integer userId, String password) {
        UserLoginAccountEntity userLoginAccountEntity = userLoginAccountService.selectOne(new EntityWrapper<UserLoginAccountEntity>().eq("user_id", userId));
        String loginPassword = PasswordUtil.getMemberPassword(MD5.getMD5Code(password), userLoginAccountEntity.getLoginAccount(), userLoginAccountEntity.getCreatetime().toString());
        userLoginAccountEntity.setLoginPassword(loginPassword);
        Integer result = userLoginAccountDao.update(userLoginAccountEntity, new EntityWrapper<UserLoginAccountEntity>()
                .eq("user_id", userId)
        );
        Map<String, Object> map = new HashMap<String, Object>();
        if (result > 0) {
            map.put("code", 0);
            map.put("msg", "重置密码成功！");
            return map;
        }
        map.put("code", 1);
        map.put("msg", "重置密码失败！");
        return map;
    }

    @Override
    public List<String> getMobileByDays(int days) {
        return userBaseInfoDao.getMobileByDays(days);
    }

    /**
     * 查询会员的推荐会员
     *
     * @param userId
     * @return
     */
    @Override
    public UserBaseInfoEntity selectReferralsMember(Integer userId) {
        return baseMapper.selectReferralsMember(userId);
    }

    private PageUtils selectAllList(Map<String, Object> params) {
        Page<UserBaseInfoVO> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<UserBaseInfoVO> list = userBaseInfoDao.getAllUserInfo(page, params);
        page.setRecords(list);
        return new PageUtils(page);
    }

    private PageUtils selectAllListMall(Map<String, Object> params) {
        Page<UserBaseInfoVO> page = new Page<>();
        page.setCurrent(Integer.valueOf(params.get("page").toString()));
        page.setSize(Integer.valueOf(params.get("limit").toString()));
        List<UserBaseInfoVO> list = userBaseInfoDao.getAllUserInfoMall(page, params);
        page.setRecords(list);
        return new PageUtils(page);
    }

    private int deleteUsers(String ids) {
        String[] array = ids.split(",");
        return userBaseInfoDao.deleteUser(array);
    }

    @Override
    public Integer getCountByIds(String[] ids) {
        return userBaseInfoDao.getCountByIds(ids);
    }

    @Override
    public Integer getByName(String name) {
        return userBaseInfoDao.getByName(name);
    }

    @Override
    public R addMem(String name, String password, String mobile) {
        //组装参数
        RegisterParamDto registerParamDto = new RegisterParamDto();
        registerParamDto.setUserType(0);
        registerParamDto.setAccount(name);
        registerParamDto.setPhone(mobile);
        registerParamDto.setPassword(MD5.getMD5Code(password));
        registerParamDto.setRegisterSource("erp");
        //调用接口
        UcenterResult<UserInfo> result = userLoginServicel.registerByErp(AppType.erp, registerParamDto);
        UserInfo userInfo = new UserInfo();
        if (result != null && result.getCode() == UcenterResult.success().getCode()) {
            userInfo = result.getData();
            return R.ok();
        } else {
            return R.error(result.getMessage());
        }
    }

    @Override
    public Integer count(String param) {
        String[] split = param.split(",");
        return userBaseInfoDao.count(split);
    }


}
